package com.gds.wiki.cloud.admin.server.security.oauth2.core.authenticator;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gds.wiki.cloud.admin.client.sys.model.AdminUser;
import com.gds.wiki.cloud.admin.server.modular.sys.service.AdminUserService;
import com.gds.wiki.cloud.framework.common.exception.BizExceptionEnum;
import com.gds.wiki.cloud.framework.common.exception.BusinessException;
import com.gds.wiki.cloud.oauth2.common.integration.IntegrationAuthentication;
import com.gds.wiki.cloud.oauth2.common.integration.authenticator.AbstractPreparableIntegrationAuthenticator;
import com.gds.wiki.cloud.oauth2.common.model.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 默认登录处理
 * @author WIKI
 * @date 2018-3-31
 **/
@Component
@Primary
public class UsernamePasswordAuthenticator extends AbstractPreparableIntegrationAuthenticator {

    @Autowired
    private AdminUserService userApi;


    @Override
    public SecurityUser authenticate(IntegrationAuthentication integrationAuthentication){
        String username=integrationAuthentication.getAuthParameter("username");
        String password=integrationAuthentication.getAuthParameter("password");
        if(StrUtil.isEmpty(username)){
            throw new BusinessException(BizExceptionEnum.LOGIN_USERNAME_ERROR);
        }
        if(StrUtil.isEmpty(password)){
            throw new BusinessException(BizExceptionEnum.LOGIN_PASSWORD_NULL);
        }

            AdminUser user=new AdminUser();
            user.setLoginname(integrationAuthentication.getUsername());
            user = userApi.getOne(new QueryWrapper<>(user));
            if(user==null){
                throw new BusinessException(BizExceptionEnum.NO_THIS_USER);
            }

            SecurityUser securityUser=new SecurityUser(user.getLoginname(),user.getPassword());
            securityUser.setId(user.getId());
            securityUser.setDeptId(user.getDeptId());
            return securityUser;
    }

    @Override
    public void prepare(IntegrationAuthentication integrationAuthentication) throws BusinessException {


    }

    @Override
    public boolean support(IntegrationAuthentication integrationAuthentication) {
        return StringUtils.isEmpty(integrationAuthentication.getAuthType());
    }
}
